var ERRORS_KEY = 'signinErrors';

Template.signin.onCreated(function() {
  Session.set(ERRORS_KEY, {});
});

Template.signin.helpers({
  errorMessages: function() {
    return _.values(Session.get(ERRORS_KEY));
  },
  errorClass: function(key) {
    return Session.get(ERRORS_KEY)[key] && 'error';
  }
});

Template.signin.events({
  'submit': function(event, template) {
    event.preventDefault();

    var email = template.$('[id=inputPhone]').val();
    var password = template.$('[id=inputPassword]').val();

    var errors = {};

    if (! email) {
      errors.email = '请输入手机号!';
    }

    if (! password) {
      errors.password = '请输入密码！';
    }

    Session.set(ERRORS_KEY, errors);
    if (_.keys(errors).length) {
      return;
    }

    Meteor.loginWithPassword(email, password, function(error) {
      if (error) {
        return Session.set(ERRORS_KEY, {'none': error.reason});
      }

      Router.go('/');
    });
  }
});


var ERRORS_KEY = 'joinErrors';

Template.join.onCreated(function() {
  Session.set(ERRORS_KEY, {});
});

Template.join.helpers({
  errorMessages: function() {
    return _.values(Session.get(ERRORS_KEY));
  },
  errorClass: function(key) {
    return Session.get(ERRORS_KEY)[key] && 'error';
  }
});

Template.join.events({
  'submit': function(event, template) {
    event.preventDefault();
    var email = template.$('[id=inputPhone]').val();
    var password = template.$('[id=inputPassword]').val();
    var confirm = template.$('[id=inputrePassword]').val();

    var errors = {};

    if (!Meteor.regexp.phone.test(email)) {
      errors.email = '请输入正确格式手机号 ! ';
    }else if (!Meteor.regexp.password.test(password)) {
      errors.password = '请输入字母数字组成的6-12位密码 ！';
    } else if (confirm !== password) {
      errors.confirm = '请确认密码和密码一致!';
    }

    Session.set(ERRORS_KEY, errors);
    if (_.keys(errors).length) {
      return;
    }

    Accounts.createUser({
      username: email,
      password: password
    }, function(error,res) {
      if (error && error.reason=="Username already exists.") {
        return Session.set(ERRORS_KEY, {'none': "手机号已经注册"});
      }
      Meteor.loginWithPassword(email,password,function (err) {
        if(err){
          throw new Meteor.Error("登录","登录失败.");
          // return throw new Meteor.Error("登录","登录失败.")
        }
        Router.go('/');
      })
    });
    return false;
  }
});
